//订单列表
var $orderTable = $('#orderTableList');
var contractTypeDate='' //选择类型
var $refundTable = $('#refundTable')

//防止表头与表格不对齐
$(window).resize(function () {
    $orderTable.bootstrapTable('resetView');
});

$(function () {
    // 初始化下拉菜单
    $('.filter-content select').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });
    // 初始化日期选择控件
    $('.date-input').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //初始化订单列表
    orderTableListInit()

    // 高级筛选
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetOrderQueryParams('#filterContent');
    });

    $('#paidBackStatusMultiple').multiselect({
        includeSelectAllOption: true,
        selectAllText:" 全部",
        buttonText: function() {
            return '回款状态';
        },
        onDropdownShow: function (t) {
            $('#paidBackStatusMultiple').multiselect('deselectAll', false);
            $('#paidBackStatusMultiple').multiselect('updateButtonText');
        },
        onDropdownHide: function (t) {
            $('#paidBackStatusMultiple').multiselect('deselectAll', false);
            $('#paidBackStatusMultiple').multiselect('updateButtonText');
        },
    });
});

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    // $('.selector-box dd').find('a').removeClass("active")
    // $('.selector-box dl').find("dt").next().find('a').addClass("active")
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'lastMonth') {//上月
        $('.lastMonth').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("lastMonth");
    }
    $('#orderCompleteTmStartMin').val('');
    $('#orderCompleteTmEndMin').val('');
    $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}

/**
 * 订单列表 --分页列表页
 */
function orderTableListInit() {
    //先销毁表格
    $orderTable.bootstrapTable('destroy');
    $orderTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/order/userOrderList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderId',
        idField: 'productOrderId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', heckbox: true, valign: 'middle',width: '6%'},*/
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '52',formatter: indexFormat},
            {title: '订单编号',field: 'orderNumber', align: 'left', valign: 'middle', sortable: true},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle', sortable: true,formatter: customerNameFormat},
            {title: '客户联系人', field: 'contactPerson', align: 'left', valign: 'middle', sortable: true,formatter: contactNameFormat},
            {title: '订单状态', field: 'orderStatus', align: 'left', valign: 'middle', sortable: true, formatter: orderStatusFormat},
            {title: '提成发放', field: 'royaltyStatus', align: 'left', valign: 'middle', sortable: true, formatter: royaltyStatusFormat},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle', sortable: true},
            {title: '订单类型', field: 'orderType', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: orderTypeFormat},
            {title: '支付方式', field: 'orderPaymentWay', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: orderPaymentWayFormat},
            {title: '订单优惠总金额', field: 'orderDiscountTotalAmount', align: 'left', valign: 'middle', visible: false, sortable: true},
            {title: '订单实际总金额', field: 'orderActualTotalAmount', align: 'left', valign: 'middle', visible: false, sortable: true},
            {title: '订单总金额', field: 'orderTotalAmount', align: 'left', valign: 'middle', visible: false, sortable: true},
            {title: '已汇款金额合计', field: 'paidBackAmount', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '附加费用', field: 'orderSurcharge', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '附加费用备注', field: 'orderSurchargeRemark', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '客户联系方式', field: 'bindMobilePhoneNumber', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '客户邮箱', field: 'customerEmail', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '是否合作开发', field: 'whetherCoDevelopment', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: whetherCoDevelopmentFormat},
            {title: '是否全部到款', field: 'whetherAllPayment', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: whetherAllPaymentFormat},
            {title: '回款状态', field: 'paidBackStatus', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: paidBackStatusFormat},
            {title: '是否挂起', field: 'whetherSuspend', align: 'left', valign: 'middle', sortable: true, visible: false, formatter: whetherSuspend},
            {title: '合同编号', field: 'contractNumber', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '订单完成时间', field: 'orderCompleteTm', align: 'left', valign: 'middle', sortable: true, visible: false},
            {title: '操作',field: 'operate',align: 'right',events: operateEvents,formatter: genderOpt},
            {title: '客户ID', field: 'customerId', visible: false}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 1, 4, 5, 6, 7],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
            tableNav();
        },

        onPostBody: function (data) {
            //console.log(data);
            var orderTotalAmountTotal = 0;// 总计金额
            var royaltyMoneyTotal = 0;// 提成金额
            for (var i = 0; i < data.length; i++) {
                orderTotalAmountTotal +=  Number(data[i].orderTotalAmount) * Number(100);
                royaltyMoneyTotal += Number(data[i].royaltyMoney) * Number(100);
            }
            var totalOrderAmount = formatPrice(orderTotalAmountTotal / Number(100))+" ￥";
            var totalRoyaltyMoney = formatPrice(royaltyMoneyTotal / Number(100))+" ￥";
            $('#orderTotalAmountTotal').text(totalOrderAmount);
            $('#royaltyMoneyTotal').text(totalRoyaltyMoney);
            $('#totalOrderAmount').text(formatAmount(totalOrderAmount));
            $('#totalRoyaltyMoney').text(formatAmount(totalRoyaltyMoney));
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
    tableNav();
}

//选择显示或隐藏Column
function hideOrShowColumn(columnName,status) {
    if (status.checked){
        $orderTable.bootstrapTable('showColumn', columnName);
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }else{
        $orderTable.bootstrapTable('hideColumn', columnName);
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 订单状态--1:等待回款;2:已完成;3:作废;4.部分回款
 */
function orderStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>等待回款</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>已完成</span>";
    } else if (3 == value){
        return "<span class='label label-warning-light'>作废</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>部分回款</span>";
    } else if (5 == value){
        return "<span class='label label-warning-light'>预回款</span>";
    }
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else {
        return '<a href="JavaScript:void(0);" onclick=\'customerDetail(\"'+row.customerId+'")\'>'+value+'</a>';
    }

}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
* 点击联系人姓名跳转联系人详情页面
* @param value
* @param row
* @param index
* @returns {string}
*/
function contactNameFormat(value, row, index) {
    if(!value) {
        return '-';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'contactDetail(\"'+row.contactPerson+'",\"'+row.bindMobilePhoneNumber+'",\"'+row.customerId+'")\'>'+value+'</a>';
}

function  contactDetail(contactName,contactInformation,customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getContactId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId: customerId,
            contactInformation : contactInformation,
            contactName : contactName
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });

}
/**
 * 提成发放状态（1:已全部发放；2:部分发放;3:未发放）
 */
function royaltyStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        //bg-success mdi mdi-15px mdi-checkbox-marked-outline
        return "<span class='img-all grant-img' title='已全部发放' data-toggle='tooltip'>已发放</span>";
        // return "<span class='img-all grant-img' title='已全部发放' data-toggle='tooltip'><img src='/images/mdiImg/grantImg.png' alt=''></span>已发放";
    } else if (2 == value) {
        //bg-info mdi mdi-15px mdi-brightness-3
        return "<span class='img-all partial-img' title='部分发放' data-toggle='tooltip'>部分发放</span>";
    } else if (3 == value){
        //bg-danger mdi mdi-15px mdi-close <img src='/images/mdiImg/unissuedImg.png' alt=''>
        return "<span class='img-all unissued-img' title='未发放' data-toggle='tooltip'>未发放</span>";
    }
}


/**
 * 订单类型--0:非会员订单;1:会员订单
 */
function orderTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (0 == value) {
        return "<span class='label label-success-light'>非会员订单</span>";
    } else if (1 == value) {
        return "<span class='label label-info-light'>会员订单</span>";
    }
}

/**
 * 支付方式--1：线上支付;2:线下支付;3:余额支付
 */
function orderPaymentWayFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>线上支付</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>线下支付</span>";
    } else if (3 == value){
        return "<span class='label label-warning-light'>余额支付</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>银行汇款</span>";
    }
}

/**
 * 是否合作开发--1:是;2:否
 */
function whetherCoDevelopmentFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 是否全部到款--1:是;2:否
 */
function whetherAllPaymentFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 回款状态--1:等待回款;2:已完成;3:作废;4.部分回款
 */
function paidBackStatusFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>等待回款</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>已完成</span>";
    } else if (3 == value){
        return "<span class='label label-warning-light'>作废</span>";
    } else if (4 == value){
        return "<span class='label label-purple-light'>部分回款</span>";
    } else if (5 == value){
        return "<span class='label label-warning-light'>预回款</span>";
    }
}

/**
 * 是否挂起--1:是;2-否
 */
function whetherSuspend(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>是</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>否</span>";
    }
}

/**
 * 拼接订单表格查询条件参数
 */
function advancedQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; lastMont:上月; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //高级搜索条件
    params.orderNumber = $.trim($('#orderNumber').val());//订单编号
    params.orderStatus = $.trim($('#orderStatus').val());//订单状态
    params.orderType = $.trim($('#orderType').val());//订单类型
    params.orderPaymentWay = $.trim($('#orderPaymentWay').val());//支付方式
    //订单优惠总金额
    params.orderDiscountTotalAmountStart = $.trim($('#orderDiscountTotalAmountStart').val());
    params.orderDiscountTotalAmountEnd = $.trim($('#orderDiscountTotalAmountEnd').val());
    //订单实际总金额
    params.orderActualTotalAmountStart = $.trim($('#orderActualTotalAmountStart').val());
    params.orderActualTotalAmountEnd = $.trim($('#orderActualTotalAmountEnd').val());
    //订单总金额
    params.orderTotalAmountStart = $.trim($('#orderTotalAmountStart').val());
    params.orderTotalAmountEnd = $.trim($('#orderTotalAmountEnd').val());
    params.bindMobilePhoneNumber = $.trim($('#bindMobilePhoneNumber').val());//客户联系方式
    params.whetherCoDevelopment = $.trim($('#whetherCoDevelopment').val());//是否合作开发
    params.whetherAllPayment = $.trim($('#whetherAllPayment').val());//是否全部到款
    params.paidBackStatus = $.trim($('#paidBackStatus').val());//回款状态
    params.whetherSuspend = $.trim($('#whetherSuspend').val());//是否挂起
    params.contractNumber = $.trim($('#contractNumber').val());//合同编号
    //订单完成时间
    params.orderCompleteTmStart = $.trim($('#orderCompleteTmStart').val());
    params.orderCompleteTmEnd = $.trim($('#orderCompleteTmEnd').val());
    //params.companyName = $.trim($('#companyName').val());//所属分公司
    params.customerName = $.trim($('#customerName').val());//客户名称
    //params.userName = $.trim($('#userName').val());//创建人
    //创建时间
    params.createTmStart = $.trim($('#createTmStart').val());
    params.createTmEnd = $.trim($('#createTmEnd').val());
    params.tabType = $('#tabNumber').val();//tab页 0-全部订单 1-会员产品订单 2-非会员产品订单
    params.contactPerson = $.trim($('#contactPerson').val());//客户联系人
    $('#orderCompleteTmStartMin').val($.trim($('#orderCompleteTmStart').val()));
    $('#orderCompleteTmEndMin').val($.trim($('#orderCompleteTmEnd').val()));

    return params;
}
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; lastMonth:上月; thisWeek:本周; thisMonth:本月; thisYear:本年)
    //普通搜索条件
    params.tabType = $('#tabNumber').val();//tab页 0-全部订单 1-会员产品订单 2-非会员产品订单
    params.orderNumber = $.trim($('#orderNumberMin').val());//订单编号
    //订单完成时间
    params.orderCompleteTmStart = $.trim($('#orderCompleteTmStartMin').val());
    params.orderCompleteTmEnd = $.trim($('#orderCompleteTmEndMin').val());
    var paidBackStatusMultiple = $('#paidBackStatusMultiple').val();
    if(paidBackStatusMultiple){
        params.paidBackStatusMultiple = JSON.stringify(paidBackStatusMultiple);//回款状态
    }
    if(contractTypeDate!=''){
        params.contractType=contractTypeDate
    }

    return params;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    //console.log((row.paidBackStatus == 2 || row.paidBackStatus == 4) && row.contractOtherType != 1);
    if(row.paidBackStatus == 3 || row.paidBackStatus == 1){
        return [
            '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>',
            '<div class="dropdown">',
            '<button type="button" id="followUp" onclick="goOnline(1, \''+row.productOrderId+'\')" class="btn btn-default btn-widen" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>申请开票</button>' +
            // '<ul class="dropdown-menu">',
            // '<li><a href="JavaScript:void(0);">电子发票</a></li>',
            // '<li><a href="JavaScript:void(0);" onclick="goOnline(1, \''+row.productOrderId+'\')">纸质发票</a></li>',
            // '</ul>' +
            '</div>',
        ].join('');
    }else if(row.paidBackStatus == 2 || row.paidBackStatus == 4){
        if(row.contractOtherType != 1 && row.contractStatus == 2) {
            return [
                '<button class="btn btn-default" id="refund"><i class="mdi mdi-replay"></i>退款</button>',
                '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>',
                '<div class="dropdown">',
                '<button type="button" id="followUp" onclick="goOnline(1, \''+row.productOrderId+'\')" class="btn btn-default btn-widen" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>申请开票</button>' +
                // '<ul class="dropdown-menu">',
                // '<li><a href="JavaScript:void(0);">电子发票</a></li>',
                // '<li><a href="JavaScript:void(0);" onclick="goOnline(1, \''+row.productOrderId+'\')">纸质发票</a></li>',
                // '</ul>' +
                '</div>',
            ].join('');
        }else{
            return [
                '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>',
                '<div class="dropdown">',
                '<button type="button" id="followUp" onclick="goOnline(1, \''+row.productOrderId+'\')" class="btn btn-default btn-widen" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>申请开票</button>' +
                // '<ul class="dropdown-menu">',
                // '<li><a href="JavaScript:void(0);">电子发票</a></li>',
                // '<li><a href="JavaScript:void(0);" onclick="goOnline(1, \''+row.productOrderId+'\')">纸质发票</a></li>',
                // '</ul>' +
                '</div>',
            ].join('');
        }

    }else if(row.paidBackStatus =='5'){
        return '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>'
    }
   /* let html = '';
        html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    return html;*/
}

/**
 * 功能：跳转线上线下电话跟进
 * 参数：1-线上电话  2-拜访  3-微信  4-线下电话  5-邮箱  6-陪访
 * */
function goOnline(type, orderId) {
    var title = '申请开票';
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: title,
        url: "/front/orderManager/user/applyInvoice?type=" + type + "&orderId=" +orderId
    }, true);
}


/**
 * 自定义操作列事件
 */
var getProductOrderId;
var getPaidBackStatus;
window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '订单详情',
            url : "/front/orderManager/orderDetail?productOrderId=" + row.productOrderId +"&contractId="+ row.contractId
        }, true);
    },
    //编辑点击事件
    'click #edit': function (e, value, row, index) {

    },
    //退款点击事件
    'click #refund': function (e, value, row, index) {
        $('#additionalFees').text(row.orderSurcharge == null?'0':row.orderSurcharge);
        console.log(row.orderSurcharge)
        // debugger;
        if(row.orderSurcharge == 0 || row.orderSurcharge == null  && row.paidBackStatus == 2){
            $('#additionalFeesBox').hide()
        }else{
            $('#additionalFeesBox').show()
        }
        $("input[name='additionalFeesCheck']").prop('checked',false);
        if(row.paidBackStatus == 4){
            $('#additionalFeesCheck').hide()
        }else{
            $('#additionalFeesCheck').show()
        }
        $('#refundRemark').val('')
        $('#refundModal').modal('show');
        getProductOrderId = row.productOrderId;
        refundTableInit();
        getPaidBackStatus = row.paidBackStatus;
        if(row.paidBackStatus == 4){
            var  columnsArray = [
                {title: '主键', field: 'productOrderDetailId', visible: false},
                /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',width: '6%'},*/
                {title: '产品名称',field: 'orderDetailName', align: 'left', valign: 'middle'},
                {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
                {title: '会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
                {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
                {title: '数量', field: 'productQuantity', align: 'left', valign: 'middle'},
                {title: '单价', field: 'productUnitPrice', align: 'left', valign: 'middle',visible: false},
                {title: '优惠价', field: 'productPreferentialPrice', align: 'left', valign: 'middle',visible: false},
                {title: '创建人id', field: 'createPeopleId', align: 'left', valign: 'middle',visible: false},
                {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle',visible: false},
                {title: '订单id', field: 'productOrderId', align: 'left', valign: 'middle',visible: false},
                // {title: '全选', field: 'royaltyStatus', align: 'left', valign: 'middle',checkbox: true},
            ]
            $refundTable.bootstrapTable('refreshOptions', {url:'/order/selectCustomerProductOrderDetailList',columns:columnsArray,pageNumber: 1, queryParams: refundQueryParams});
        }else if(row.paidBackStatus == 2){
            var  columnsArray1 = [
                {title: '主键', field: 'finishOrderProductId', visible: false},
                /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',width: '6%'},*/
                {title: '产品名称',field: 'productName', align: 'left', valign: 'middle'},
                {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
                {title: '会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
                {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
                // {title: '数量', field: 'productQuantity', align: 'left', valign: 'middle'},
                {title: '单价', field: 'productUnitPrice', align: 'left', valign: 'middle',visible: false},
                {title: '优惠价', field: 'productPreferentialPrice', align: 'left', valign: 'middle',visible: false},
                {title: '创建人id', field: 'createPeopleId', align: 'left', valign: 'middle',visible: false},
                {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle',visible: false},
                {title: '订单id', field: 'productOrderId', align: 'left', valign: 'middle',visible: false},
                {title: '选择', field: '选择',class:'checkedName', align: 'left', valign: 'middle',checkbox: true},
            ]

            $refundTable.bootstrapTable('refreshOptions', {url:'/order/finishOrderBackProductList',columns:columnsArray1,pageNumber: 1, queryParams: function(params){
                    params.pageSize = params.limit;
                    params.pageIndex = (params.offset / params.limit) + 1;
                    params.sortName = params.sort; //排序列名
                    params.sortOrder = params.order;//排序方式
                    params.orderId = row.productOrderId;
                    return params;
            }});
            $('.checkedName').html('<div class="th-inner ">选择</div>')

        }
        $('#refundAmount').val('')
    },
};

/**
 * 搜索点击事件
 */

function searchOrderList(type,value){
    // $('.all').addClass('active-second');
    // $('.lastMonth').removeClass('active-second');
    // $('.week').removeClass('active-second');
    // $('.month').removeClass('active-second');
    // $('.year').removeClass('active-second');
    // $("#dateType").val("all");

    if (type === 1) {//普通条件查询
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }  else if (type == 3) {//选择类型
        contractTypeDate=value
        $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: function(params){
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.dateType = $('#dateType').val();//dateType(all:全部; lastMonth:上月; thisWeek:本周; thisMonth:本月; thisYear:本年)
                //普通搜索条件
                params.tabType = $('#tabNumber').val();//tab页 0-全部订单 1-会员产品订单 2-非会员产品订单
                //params.orderNumber = $.trim($('#orderNumberMin').val());//订单编号
                //订单完成时间
                //params.orderCompleteTmStart = $.trim($('#orderCompleteTmStartMin').val());
                //params.orderCompleteTmEnd = $.trim($('#orderCompleteTmEndMin').val());
                params.contractType = value;
                return params;
            }});
    }

    // 选择类型击切换背景
    $('.selector-box').on('click', 'a', function () {
        $(this).parents('dl').find('a').removeClass('active');
        $(this).addClass('active');
    });

}

/**
 * 重置订单清单查询条件
 */
function resetOrderQueryParams(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    /*searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');*/

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        orderTableListInit();
    }
}

//清空所有搜索条件
function clearAllData() {
    //全部 上月 本周 本月 本年
    $('.all').addClass('active-second');
    $('.lastMonth').removeClass('active-second');
    $('.year').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    //订单编号
    $('#orderNumberMin').val('');
    $('#orderCompleteTmStartMin').val('');
    $('#orderCompleteTmEndMin').val('');
    $('.filter-content input').val('')
    $('.filter-content select').val('').selectpicker('refresh');
}

/**
 * 显示隐藏金额
 * @param id
 * @param name
 */
function amountEye(id,name){
    var $img = $("#" + id);
    var flag = $($img).attr('data-flag');
    $($img).attr('src', '/images/login/password-' + flag + '.png');
    $($img).attr('data-flag', flag == 'show' ? 'hide' : 'show');
    $($img).attr('title', flag == 'show' ? '隐藏金额' : '显示金额');
    if (flag == 'show'){
        $('#showAmount').css('display', 'block');
        $('#hideAmount').css('display', 'none');
    } else {
        $('#hideAmount').css('display', 'block');
        $('#showAmount').css('display', 'none');
    }
}

// 切换tab
function changeTableModel(str) {
    // 点击Tab切换收起高级搜
    $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
        resetOrderQueryParams('#filterContent');
    });
    clearAllData();
    // $('#' + str).parents('li').addClass('active').siblings('li').removeClass('active');
    if (str == 'allProductOrder') {
        $('.allProductOrder').addClass('active-second');
        $('.memberProductOrder').removeClass('active-second');
        $('.nonMemberProductOrder').removeClass('active-second');
        $('#contractType').css('display', 'none');
        $('#tabNumber').val('0');
    }
    if (str == 'memberProductOrder') {
        $('.memberProductOrder').addClass('active-second');
        $('.allProductOrder').removeClass('active-second');
        $('.nonMemberProductOrder').removeClass('active-second');
        $('#contractType').css('display', 'block');
        $('#tabNumber').val('1');
        $('.selector-box').find('a').removeClass('active');
        $('.selector-box').find('dl').children("dd:eq(0)").find('a').addClass('active');

    }
    if (str == 'nonMemberProductOrder') {
        $('.nonMemberProductOrder').addClass('active-second');
        $('.allProductOrder').removeClass('active-second');
        $('.memberProductOrder').removeClass('active-second');
        $('#contractType').css('display', 'none');
        $('#tabNumber').val('2');
    }
    $orderTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}

function filterSearch(){
    var tabNumber = $('#tabNumber').val();
    if (tabNumber == "1") {
        $('#orderNumberSearch').css('display', 'none');
        $('#contractNumberSearch').css('display', 'none');
        $('#customerNameSearch').css('display', 'block');
        $('#contactPersonSearch').css('display', 'block');
        $('#bindMobilePhoneNumberSearch').css('display', 'none');
        $('#orderDiscountTotalAmountSearch').css('display', 'none');
        $('#orderTotalAmountSearch').css('display', 'block');
        $('#whetherCoDevelopmentSearch').css('display', 'block');
        $('#createTmSearch').css('display', 'none');
        $('#orderCompleteTmSearch').css('display', 'block');
    } else {
        $('#orderNumberSearch').css('display', 'block');
        $('#contractNumberSearch').css('display', 'block');
        $('#customerNameSearch').css('display', 'block');
        $('#contactPersonSearch').css('display', 'block');
        $('#bindMobilePhoneNumberSearch').css('display', 'block');
        $('#orderDiscountTotalAmountSearch').css('display', 'block');
        $('#orderTotalAmountSearch').css('display', 'block');
        $('#whetherCoDevelopmentSearch').css('display', 'none');
        $('#createTmSearch').css('display', 'block');
        $('#orderCompleteTmSearch').css('display', 'block');
    }
}

/**
 * 金额格式化函数
 * 将字符串中的整数或者浮点数格式化为千分位表示
 * 示例：formatPrice('$9999999'); // output $9,999,999
 *		formatPrice('今天我赚了$1000块'); // output 今天我赚了$1,000块
 *		formatPrice('今天我赚了$3000块，吃饭花了$100，给妹纸$1888零花钱'); // 今天我赚了$3,000块，吃饭花了$100，给妹纸$1,888零花钱
 * 		formatPrice('12345678.8654321'); //output "12,345,678.8654321"
 *		formatPrice('12345678.8654321.'); //output "12,345,678.8654321."
 *		formatPrice('12345678.8654321.6766'); //output "12345678.8654321.6766" 非标准浮点数，跳过
 * @param String|Number str 原始字符串或金额
 *
 */
function formatPrice(str){
    return String(str).replace(/\d+(?:\.\d+)*/g,function(price){
        var arr=price.split('.');
        if(arr.length>2){
            return price;
        }
        arr[0]=arr[0].replace(/(\d{1,3})(?=(\d{3})+$)/g, '$1,');
        return arr.join('.');
    });
}

/**
 * 将所有数字替换成*
 * @param number
 * @returns {string}
 */
function formatAmount(number) {
    return String(number).replace(/\d+(?:\.\d+)*/g,function(price){
        var arr=price.split('.');
        if(arr.length>2){
            return price;
        }
        arr[0]=arr[0].replace(/(\d)/g, '*');
        if(arr.length>1){
            arr[1]=arr[1].replace(/(\d)/g, '*');
        }
        return arr.join('.');
    });
}

/*
//显示导入订单模态框
function showImportOrderModal(){
    $('#importOrderModal').modal('show');
}

//取消导入订单模态框
function cancelImportOrderList() {
    $("#importOrderFile").val("");
}

//导入订单
function importOrderList() {
    if(!document.getElementById('importOrderFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importOrderFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importOrderFile")[0].files[0]);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX" || fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/customerProductOrderImport/import',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    //订单导入数量
                    var importNum = data.data.importNum;
                    var repeatIdStr = data.data.repeatIdStr;
                    var importFailIdStr = data.data.importFailIdStr;
                    var contractNotExist = data.data.contractNotExist;
                    var customerNotExist = data.data.customerNotExist;
                    var otherOrders = data.data.otherOrders;
                    var ownerNull = data.data.ownerNull;

                    //返回内容
                    var content = "";

                    //导入数量大于0
                    if(importNum > 0){
                        content = "成功导入"+importNum+"条数据";
                    }
                    //重复id不为空
                    if(repeatIdStr != ""){
                        content = content + "<br>订单为第：" + repeatIdStr + "行数据，数据库已存在";
                    }
                    //失败id不为空
                    if(importFailIdStr != ""){
                        content = content + "<br>订单为第：" + importFailIdStr + "行数据导入失败";
                    }

                    //合同不存在不为空
                    if(contractNotExist != ""){
                        content = content + "<br>订单为第：" + contractNotExist + "行数据导入失败，合同不存在";
                    }

                    //客户不存在不为空
                    if(customerNotExist != ""){
                        content = content + "<br>订单为第：" + customerNotExist + "行数据导入失败，客户不存在";
                    }

                    //非生效中的其它订单不为空
                    if(otherOrders != ""){
                        content = content + "<br>订单为第：" + otherOrders + "行数据导入失败，只导入回款状态为已回款并且订单状态为生效中或者已结束的订单";
                    }

                    //所有人不存在不为空
                    if(ownerNull != ""){
                        content = content + "<br>订单为第：" + ownerNull + "行数据导入失败，所有人不存在";
                    }

                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importOrderFile").val("");
                                    $orderTable.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importOrderModal').modal('hide');
                    $("#importOrderFile").val("");
                } else {
                    $.alert("导入失败");
                    $("#importOrderFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importOrderFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx文件！',
        });
    }
}

//导入失败日志
function openLogPage() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '导入失败日志',
        url: "/front/orderManager/orderImportFailureLog"
    }, true);
}*/



/**
 * 退款列表
 */
function refundTableInit() {
    //先销毁表格
    $refundTable.bootstrapTable('destroy');
    $refundTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        // url: '/order/selectCustomerProductOrderDetailList',//请求地址
        url:'',
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: true,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
    // "    uniqueId: 'productOrderId',
    //     idField: 'productOrderId',"
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [5,10,15,20],//可供选择的每页的行数
        queryParams: refundQueryParams,//查询参数
        columns: [
            {title: '主键', field: 'productOrderDetailId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',width: '6%'},*/
            {title: '产品名称',field: 'orderDetailName', align: 'left', valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '数量', field: 'productQuantity', align: 'left', valign: 'middle'},
            {title: '单价', field: 'productUnitPrice', align: 'left', valign: 'middle',visible: false},
            {title: '优惠价', field: 'productPreferentialPrice', align: 'left', valign: 'middle',visible: false},
            {title: '创建人id', field: 'createPeopleId', align: 'left', valign: 'middle',visible: false},
            {title: '创建时间', field: 'createTm', align: 'left', valign: 'middle',visible: false},
            {title: '订单id', field: 'productOrderId', align: 'left', valign: 'middle',visible: false},
            {title: '全选', field: 'royaltyStatus', align: 'left', valign: 'middle',checkbox: true},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onCheck:function(row){
           $("input[name='additionalFeesCheck']").prop('checked',false)
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function refundQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;

    params.productOrderId = getProductOrderId;
    params.productOrderDetailType = 4;

    return params;
}

function isAdditional(){
    $("input[name='btSelectItem']").prop('checked',false);
    $refundTable.bootstrapTable('refresh')
}

function submitRefund(){
    if(!$('#refundAmount').val()){
        $.alert('退款金额不能为空');
        return;
    }
    var params = {};
    if(getPaidBackStatus == 4){
        params = {
            productOrderId:getProductOrderId,
            orderStatus:4,
            applyBackMoney:$('#refundAmount').val(),
            sqbz:$('#refundRemark').val()
        }
        $.ajax({
            url: '/order/orderProductDetailNumMoney',
            type: 'POST',
            dataType:"json",
            contentType: "application/x-www-form-urlencoded",
            data:{
                orderId:getProductOrderId,
            },
            async:false,
            // processData: false,
            success:(function(data) {
                if(data.code == "000000") {
                    if($('#refundAmount').val()>data.data  || $('#refundAmount').val()<data.data){
                    //if($('#refundAmount').val()> data.data  || $('#refundAmount').val()<data.data){
                        $.alert({
                            title: '提示',
                            content: '退款金额必须全部，请重新输入！',
                            buttons: {
                                confirm: {
                                    text: '确认',
                                    btnClass: 'btn-primary',
                                    action: function () {
                                        $('#refundModal').modal('hide');
                                    }
                                }
                            }
                        });
                    }else{
                        orderRefund(params)
                    }

                }else{

                }
            }),
            error:(function() {

            })
        })

    }else if(getPaidBackStatus == 2){
        var row = $.map($refundTable.bootstrapTable('getAllSelections'),function (row) {
            return row;
        });
        // console.log($("input[name='additionalFeesCheck']").prop("checked"))
        if(row.length<1 && $("input[name='additionalFeesCheck']").prop("checked") == false){
            $.alert('请勾选会员产品或附加费用');
            return;
        }
        if($("input[name='additionalFeesCheck']").prop("checked") == false){
            if(Number($('#refundAmount').val())>Number(row[0].productFinalPrice * row[0].productQuantity)){
                $.alert('退款金额不能大于成交价');
                return;
            }
        }else{
            if(Number($('#refundAmount').val())>Number($('#additionalFees').text())){
                $.alert('退款金额不能大于附加费用');
                return;
            }
        }

        if($("input[name='additionalFeesCheck']").prop("checked") == false){
            params = {
                productOrderId:getProductOrderId,
                orderStatus:2,
                finishOrderProductNum:row[0].finishOrderProductNum,  //产品号
                productCode:row[0].productCode, //产品编码
                productName:row[0].productName, //产品名称
                productOriginalPrice:row[0].productOriginalPrice, //原价
                productUnitPrice:row[0].productUnitPrice, //单价
                productMemberPrice:row[0].productMemberPrice, //会员价
                productPreferentialPrice :row[0].productPreferentialPrice,//优惠价
                productFinalPrice:row[0].productFinalPrice, //成交价
                applyBackMoney:$('#refundAmount').val(),
                sqbz:$('#refundRemark').val()
            }
            orderRefund(params)
        }else{
            if($('#additionalFees').text() == 0){
                $.alert('附加费用金额为0，不可退选')
            }else{
                params = {
                    productOrderId:getProductOrderId,
                    productName:'附加费用', //产品名称
                    productFinalPrice:$('#additionalFees').text(), //成交价
                    applyBackMoney:$('#refundAmount').val(),
                    sqbz:$('#refundRemark').val()
                }
                orderRefund(params)
            }
        }
    }

}

 function orderRefund(params) {
     $.ajax({
         url: '/order/orderRefund',
         type: 'POST',
         dataType:"json",
         contentType: "application/json;charset=utf-8",
         data:JSON.stringify(params),
         processData: false,
         async:false,
         success:(function(data) {
             if(data.data == "success") {
                 $.alert({
                     title: '提示',
                     content: '申请成功！',
                     buttons: {
                         confirm: {
                             text: '确认',
                             btnClass: 'btn-primary',
                             action: function () {
                                 $('#refundModal').modal('hide');
                                 // orderTableListInit()
                             }
                         }
                     }
                 });
             }else{
                 $.alert(data.data)
                 // orderTableListInit()
             }
         }),
         error:(function() {

         })
     });
 }